<?php

namespace App\Repository\MyData;

use App\Base\BaseForm;
use App\Entity\MyData\MyDataKey;
use App\Entity\MyData\MyDataTemplate;
use App\Entity\MyData\MyDataValue;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method MyDataValue|null find($id, $lockMode = null, $lockVersion = null)
 * @method MyDataValue|null findOneBy(array $criteria, array $orderBy = null)
 * @method MyDataValue[]    findAll()
 * @method MyDataValue[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MyDataValueRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, MyDataValue::class);
    }

    /**
     * @param $entityName
     * @param $entityId
     * @param MyDataKey $myDataKey
     * @return MyDataValue|null
     */
    public function get4Entity($entityName,$entityId,MyDataKey $myDataKey)
    {
        return $this->findOneBy(array(
            "entity"=>$entityName,
            "entityId"=>$entityId,
            "myKey"=>$myDataKey
        ));
    }

    /**
     * @param MyDataTemplate $template
     * @param $entityName
     * @param $entityId
     * @return MyDataValue[]
     */
    public function getValues4Entity(MyDataTemplate $template ,$entityName,$entityId)
    {
        $templateValues = [];
        $params = $template->getMyKeys();
        foreach ($params as $oneKey) {
            $templateValues[] = $this->get4Entity($entityName,$entityId,$oneKey);
        }
        return $templateValues;
    }


    public function getForm4Entity(BaseForm &$baseForm,MyDataTemplate $template ,$entityName,$entityId)
    {
        $templateValues = [];
        $params = $template->getMyKeys();
        foreach ($params as $oneKey) {

            $record = $this->get4Entity($entityName,$entityId,$oneKey);

            switch ($oneKey->getType()) {
                case "text":
                    $func = "add".ucfirst($oneKey->getType());
                    $baseForm->$func("param_{$oneKey->getName()}",$oneKey->getLabel())->setWidth(12)->getData();

                    $templateValues["param_{$oneKey->getName()}"] = $record?$record->getValue():"";
                    break;
                case "arrayText":
                    $func = "add".ucfirst($oneKey->getType());
                    $baseForm->$func("param_{$oneKey->getName()}",$oneKey->getLabel())->setWidth(12)->getData();
                    //需要检测默认值是不是数组格式
                    if ($record) {
                        $arrayValue = json_decode($record->getValue())?:[""];
                        if (!is_array($arrayValue)) {
                            $arrayValue = [$arrayValue];
                        }
                        $dataValue = array_values($arrayValue);
                    }else{
                        $dataValue =  [""];
                    }
                    $templateValues["param_{$oneKey->getName()}"] = $dataValue;
                    break;
            }

        }
        return $templateValues;
    }

    public function saveValues(MyDataTemplate $template,$requestData ,$entityName,$entityId)
    {
        if ($template) {
            $params = $template->getMyKeys();
            foreach ($params as $oneKey) {
                $record = $this->get4Entity($entityName,$entityId,$oneKey);
                if (!$record) {
                    $record = new MyDataValue();
                    $record->setEntity($entityName)
                        ->setEntityId($entityId)
                        ->setMyKey($oneKey);
                }
                $value = $requestData["param_{$oneKey->getName()}"]??"";
                if (!is_string($value)) {
                    $value = json_encode($value);
                }
                $record->setValue($value);
                $this->_em->persist( $record);
            }
            $this->_em->flush();
        }
    }



    // /**
    //  * @return MyDataValue[] Returns an array of MyDataValue objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('m')
            ->andWhere('m.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('m.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?MyDataValue
    {
        return $this->createQueryBuilder('m')
            ->andWhere('m.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}
